<?php

class ItemsController extends BaseController {

	public function __construct()
    {
        $this->beforeFilter('isAdminGet', array('on' => 'get'));
        $this->beforeFilter('isAdminPost', array('on' => 'post'));
    }
	/**
	 * Display a listing of the resource.
	 * GET /items
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}
	public function searchItems($criteria = null)
	{
		$postcall = false;
		if($criteria == null)
		{
			$criteria = Input::get("criteria");
			$postcall = true;
		}
		$where = " 1 = 1 ";
		$params = array();

		if(isset($criteria['reference']) && trim($criteria['reference']) != "")
		{
			$where .= " and reference LIKE :reference ";
			$params['reference'] = "%".$criteria['reference']."%";
		}

		if(isset($criteria['name']) && trim($criteria['name']) != "")
		{
			$where .= " and name LIKE :name ";
			$params['name'] = "%".$criteria['name']."%";
		}

		if(isset($criteria['maxPrice']) && trim($criteria['maxPrice']) != "")
		{
			$where .= " and price <= :maxPrice ";
			$params['maxPrice'] = $criteria['maxPrice'];
		}

		if(isset($criteria['minPrice']) && trim($criteria['minPrice']) != "")
		{
			$where .= " and price >= :minPrice ";
			$params['minPrice'] = $criteria['minPrice'];
		}

		if(isset($criteria['not']) && !empty($criteria['not']))
		{
			$where .= " and pk NOT IN ( '" . implode($criteria['not'], "', '") . "' ) ";
		}
		$where .= " and deleted_at IS NULL ";
		//echo $where;
		$items = Item::whereRaw($where, $params)->get();

		if(!$postcall)
		{
			return $items;
		}
		else
		{
			return "";
		}

	}
	public function showItems()
	{
		$items = new Item;
		$reference = Input::get('reference');
		$name = Input::get('name');
		$priceFrom = Input::get('priceFrom');
		$priceTo = Input::get('priceTo');
		if($reference != "")
		{
			$items = $items->where('reference', 'LIKE', "%$reference%");
		}
		if($name != "")
		{
			$items = $items->where("name", "LIKE", "%$name%");
		}
		if($priceFrom != "" && $priceTo != "")
		{
			$items = $items->whereBetween('price', array($priceFrom, $priceTo));
		}
		elseif($priceFrom != "")
		{
			$items = $items->where("price", ">=", $priceFrom);
		}
		elseif($priceTo != "")
		{
			$items = $items->where("price", "<=", $priceTo);
		}

		$items = $items->paginate(10);
		$trashedItems = Item::onlyTrashed()->paginate(10);
		return View::make('items.inventoryHome')->with('items', $items)->with('trash', $trashedItems);
	}

	public function getItemInfo()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$item = Item::withTrashed()->find(Input::get('pk'));
			if($item == null)
			{
				$error = true;
				$message = "Error: no se encontró el item.";
			}
			else
			{
				$html = View::make('items.moreInfoPopup')->with('item', $item)->render();
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "html" => $html);
		}
		return json_encode($response);
	}

	public function getItemEdit()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$item = Item::find(Input::get('pk'));
			if($item == null)
			{
				$error = true;
				$message = "Error: no se encontró el item.";
			}
			else
			{
				$html = View::make('items.editPopup')->with('item', $item)->render();
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "html" => $html, "item"=>$item->toJson());
		}
		return json_encode($response);
	}

	public function getItemCreate()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		try
		{
			$html = View::make('items.createPopup')->render();
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$item = new Item;
			$response = array("error" => $error, "html" => $html, "item"=>"{}");
		}
		return json_encode($response);
	}
	public function savePicture()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		$pk = Input::get('pk');
		try
		{
			$item = null;
			if(Input::get('pk') != null)
			{
				$item = Item::find(Input::get('pk'));
			}
			
			$notFound = !Input::get('pk') == null || $item == null;
			if(!$notFound)
			{
				$error = true;
				$message= "Error: Item no encontrado.";
			}
			else
			{
				if (Input::hasFile('imageUrl')) {
				$file            = Input::file('imageUrl');
				//Validations
				$validator = Validator::make(
				    array(
				    	'image_url'=> $file
				    ),
				    array(
				    	'image_url'=> 'max:10000'
				    )
				);
				
				if($validator->fails())
				{
					$ms = "";
					foreach ($validator->messages()->all('-:message') as $message)
					{
					    $ms .= $message;
					}
					throw new Exception($ms);
					
				}


			        $parentFolderName = str_random(6);
			        
			        $destinationPath = public_path().'/img/'.$parentFolderName.'/';
			        Util::removeAllFilesFromDir($destinationPath);
			        //$filename        = str_random(6) . '_' . $item['name'].'.'.$file->guessExtension();
			        $extension = pathinfo( $file->getClientOriginalName(), PATHINFO_EXTENSION);
			        
			        //Remove current image
			        if($item->image_url != null && $item->image_url != "/img/no-pic.png")
					{
						Util::deleteDir(public_path().dirname($item->image_url));
						//$message = "deleted dir ".public_path().dirname($item->image_url);
					}

			        $filename        = str_random(6).'.'.$extension;
			        $uploadSuccess   = $file->move($destinationPath, $filename);
			        if($uploadSuccess)
			        {
			        	$item->image_url = "/img/".$parentFolderName."/".$filename;
						$item->save();
			        }
			        else
			        {
			        	$error = true;
			        	$message = "Error al guardar el archivo. Intenta de nuevo.";
			        }
			        
			    }
			    else
			    {
			    	$item->image_url = "/img/no-pic.png";
			    	$item->save();
			    	$error = true;
			    	$message = "Error: No se encontró el archivo. Intenta nuévamente.";
			    }
			}
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "message" => $message);
		}
		return json_encode($response);
	}
	public function saveItem()
	{
		$error = false;
		$message = "";
		$html;
		$response;
		$itemArray = Input::get('item');
		
		try
		{
			$item = null;
			if(isset($itemArray['pk']))
			{
				$item = Item::find($itemArray['pk']);
			}
			
			$isUpdate = isset($itemArray['pk']) && $item != null;
			$locationString = "";
			foreach(ItemLocation::all() as $location)
			{
				$locationString .= $location->pk.",";
			}
			$locationString = trim($locationString, ",");
			$validatorArray = [
							array(
							        'name' => $itemArray['name'],
							        'located_at_fk' => $itemArray['located_at_fk'],
							        'price' => $itemArray['price'],
							        'amount' => $itemArray['amount']
							    ),
							array(
							        'name' => 'required|min:2|max:249',
							        'located_at_fk' => 'required|numeric|in:'.$locationString,
							        'price' => 'required|numeric|digits_between:1,7|min:1',
							        'amount'=> 'required|numeric|min:1|digits_between:1, 13'
							    )
			];
			if(!$isUpdate)
			{
				$itemsSameReference = Item::where("reference", "=", $itemArray['reference'])->get();
				if(!$itemsSameReference->isEmpty())
				{
					throw new Exception("Ya existe un item con la referencia ".$itemArray['reference']);
					
				}
				$item = new Item;
				$item->image_url = "/img/no-pic.png";
				$validatorArray[0]['reference'] = $itemArray['reference'];
				$validatorArray[1]['reference'] = 'required|unique:items|min:1|max:249';
			}

			
			//Validations
			$validator = Validator::make($validatorArray[0], $validatorArray[1]);
			
			if($validator->fails())
			{
				$ms = "";
				foreach ($validator->messages()->all('-:message') as $message)
				{
				    $ms .= $message;
				}
				throw new Exception($ms);
				
			}

			$item->reference = $itemArray['reference'];
			$item->name = $itemArray['name'];
			$item->created_by_fk = Auth::user()->pk;
			$item->located_at_fk = $itemArray['located_at_fk'];
			$item->price = $itemArray['price'];
			$item->amount = $itemArray['amount'];
			$item->save();
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error, "pk"=> $item->pk);
		}
		return json_encode($response);
	}

	public function deleteItem()
	{
		$error = false;
		$message = "";
		$response;
		try
		{
			$item = Item::find(Input::get('item'));
			if($item != null)
			{
				$requests = $item->requests;
				if($requests == null || $requests->isEmpty())
				{
					$item->forceDelete();
					
				}
				else
				{
					$item->image_url = "/img/no-pic.png";
					$item->save();
					$item->delete();
				}
				if($item->image_url != "/img/no-pic.png")
				{
					Util::deleteDir(public_path().dirname($item->image_url));
				}
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}

	public function restoreItem()
	{
		$error = false;
		$message = "";
		$response;
		try
		{
			$item = Item::onlyTrashed()->find(Input::get('id'));
			if($item != null)
			{
				$item->restore();
			}
			else
			{
				throw new Exception("El item no fue encontrado. Por favor refresque la página e intente nuevamente.");
				
			}
			
		}
		catch(Exception $e)
		{
			$error = true;
			$message = "Error: ".$e->getMessage();
		}
		if($error)
		{
			$response = array("error" => $error, "message" => $message);
			
		}
		else
		{
			$response = array("error" => $error);
		}
		return json_encode($response);
	}

}